package com.tsfyun.common.base.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * =
 * HTTP请求工具类
 */
public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String post(String url, Map<String, String> params) {
        return post(url, params, "utf-8", null);
    }

    public static String post(String url, Map<String, String> params, Map<String, String> headers) {
        return post(url, params, "utf-8", headers);
    }

    public static String get(String url, Map<String, String> params) {
        return get(url, params, "utf-8");
    }

    /**
     * =
     * POST请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String post(String url, Map<String, String> params, String charsetName, Map<String, String> headers) {
        PrintWriter out = null;
        BufferedReader bufferedReader = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if (headers != null) {
                headers.forEach((k, v) -> {
                    conn.setRequestProperty(k, v);
                });
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), charsetName));
            // 发送请求参数
            StringBuffer param = new StringBuffer("");
            if (params != null && params.size() > 0) {
                params.forEach((k, v) -> {
                    if (StringUtils.isNotEmpty(param.toString())) {
                        param.append("&");
                    }
                    param.append(k + "=" + v);
                });
            }
            out.print(param.toString());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charsetName));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error(url);
            logger.error("POST请求异常：" + e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException ex) {
                logger.error(url);
                logger.error("POST请求异常：" + ex);
            }
        }
        return result;
    }

    /**
     * =
     * GET请求
     *
     * @param url
     * @param params
     * @param charsetName
     * @return
     */
    public static String get(String url, Map<String, String> params, String charsetName) {
        String result = "";
        BufferedReader bufferedReader = null;
        try {
            String urlNameString = url;
            StringBuffer param = new StringBuffer("");
            if (params != null && params.size() > 0) {
                params.forEach((k, v) -> {
                    if (StringUtils.isNotEmpty(param.toString())) {
                        param.append("&");
                    }
                    param.append(k + "=" + v);
                });
            }
            if (urlNameString.indexOf("?") == -1) {
                urlNameString += "?" + param.toString();
            } else {
                urlNameString += "&" + param.toString();
            }
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            conn.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charsetName));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error(url);
            logger.error("GET请求异常：" + e);
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (Exception ex) {
                logger.error(url);
                logger.error("GET请求异常：" + ex);
            }
        }
        return result;
    }
}
